<?php
namespace Backend\Models\Car;

use Backend\Models\Base;

class Lottery extends Base
{
    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'daishu_site_lottery_log';
    }

    public function gets($limit, $offset)
    {
        $query = $this->select('*')->from(self::class)->limit($limit, $offset);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result)) {
                $prize = self::getPrizeName();
                $out   = [];
                foreach ($prize as $k => $v) {
                    $out[$v['id']] = $v['name'];
                }
                foreach ($result as $k => $v) {
                    if (array_key_exists($v['prize_id'], $out)) {
                        $result[$k]['prize_id'] = $out[$v['prize_id']];
                    }
                }
                return $result;
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function getCount()
    {
        $query = $this->select('count(*) AS cnt')->from(self::class);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result) && count($result) > 0) {
                return $result[0]['cnt'];
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function remove($id)
    {
        try {
            if (!is_numeric($id)) {
                return false;
            }
            $this->db()->begin();
            $prize = $this->db()->query("SELECT * FROM `daishu_site_lottery_log` WHERE `id`={$id}")->fetch();
            if ($this->db()->execute("UPDATE  daishu_site_lottery_prize SET `number` = number +1  WHERE `id`={$prize['id']}") === false) {
                $this->db()->rollback();
                return false;
            };
            if ($this->db()->delete(self::getSource(), sprintf('id=%d LIMIT 1', intval($id))) === false) {
                $this->db()->rollback();
                return false;
            }
            $mKey = md5('get_prize_id' . $prize['prize_id']);
            //获取白名单
            $white     = self::getsLog();
            $white     = array_merge($white, [['uid' => $prize['uid'], 'phone' => $prize['phone']]]);
            $whiteList = array_column($white, 'phone', 'uid');
            //获取预约抽奖的人
            $users    = self::getsSubscribe();
            $userList = array_column($users, 'phone', 'userid');
            //生成能抽奖的人
            $lotteryUser = array_diff($userList, $whiteList);
            $user        = array_rand($lotteryUser, 1);
            self::redisServer()->rPush($mKey, $userList[$user]);
            $data = [
                'uid'      => $user,
                'phone'    => $userList[$user],
                'prize_id' => $prize['prize_id']
            ];
            if ($this->db()->insertAsDict('daishu_site_lottery_log', $data) == false) {
                $this->db()->rollback();
                return false;
            };
            $this->db()->commit();
            return true;
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function getPrizeName()
    {
        return $this->db()->query('SELECT `id`,`name` FROM `daishu_site_lottery_prize`')->fetchAll();
    }

    public static function redisServer()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        return $redis;
    }

    public function getsSubscribe()
    {
        $query = 'SELECT `userid`,`phone` FROM `daishu_appointment`';
        try {
            $ret = $this->db()->query($query)->fetchAll();
            if ($ret !== false && is_array($ret) && count($ret) > 0) {
                return $ret;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * 获取白名单
     * @return array|bool
     */
    public function getsLog()
    {
        $query = 'SELECT `uid`,`phone` FROM `daishu_site_lottery_log`';
        try {
            $ret = $this->db()->query($query)->fetchAll();
            if ($ret !== false && is_array($ret) && count($ret) > 0) {
                return $ret;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

}
